package com.qianfeng.smartplatform.controller.advice;/*
 *@Description:
 *@author:赵健
 *@Date:zjzzz 2022/9/7 17:57
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.constans.ResultCode;
import com.qianfeng.smartplatform.dto.R;
import com.qianfeng.smartplatform.exceptions.MyBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
public class MyControllerAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    // 处理我们的自定义异常的
    @ExceptionHandler(MyBaseException.class)
    public R processBaseException(MyBaseException exception) {
        exception.printStackTrace();
        return R.getResult(exception.getCode(), exception.getMessage());
    }


    //处理请求参数校验的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R processMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        try {
            //将我们自定义的异常字符串转成map,然后从里面获取到我们传递的code和msg
            Map map = objectMapper.readValue(defaultMessage, Map.class);
            return R.getResult((Integer) map.get("code"), (String) map.get("msg"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return R.ERROR();
    }

    @ExceptionHandler(Exception.class)
    public R processBaseException(Exception exception) {
        exception.printStackTrace();
        return R.getResult(ResultCode.FAIL, "网络异常,请检查您的网络");
    }
}
